
const db = require('db');
const { getTokenInof } = require('tools/token');
const isLeader = require('tools/isLeader');
const log = require('tools/log');

module.exports = async ctx => {
    const { connection, run } = db.init();
    try {
        ctx.status = 200;
        ctx.body = {
            list: await list(ctx, run),
            pagination: await pagination(ctx, run)
        };
    } catch (error) {
        ctx.status = 500;
        log(error);
        ctx.body = error
    }
    connection.end();
};

async function list(ctx, run) {
    const result = await run(`
        SELECT id,clientName,commercialSpecialistId,commercialSpecialistName,source,directions,manner
        FROM client 
        WHERE 0=0
        ${toLimit(ctx.request.body.pagination)}
    `);

    if (result.err) {
        throw result.err
    } else {
        return result.rows
    }
}

async function pagination(ctx, run) {
    const body = ctx.request.body;
    const pagination = body.pagination;
    const sqlStr = `
        SELECT COUNT(id) as total
        FROM client
        WHERE 0=0
    `
    const result = await run(sqlStr);
    if (result.err) {
        throw result.err
    }

    return {
        ...pagination,
        total: result.rows[0].total
    };
}

//---------------------------------------------------------------------------
/** 分页语句 */
function toLimit(pagination) {
    const { current = 1, pageSize = 10 } = pagination || {};
    return `LIMIT ${(current - 1) * pageSize},${pageSize}`;
}

/** 数据权限 */
function permission(ctx) {
    const userInfo = getTokenInof(ctx.header.authorization).userInfo;
    const isL = isLeader(userInfo);

    if (isL) return '';

    return `AND (client.commercialSpecialistId=${userInfo.userid})`
}